﻿var SectionVm = function (jsonOfObject) {
    var self = this;

    self.Id = ko.observable(0);
    self.SortOrderId = ko.observable(null);
    
    self.Name = ko.observable(null).extend({
        trimString: null,
        required: { message: "Name is a required field.", params: true },
        maxLength: { message: "Please enter less than 50 characters.", params: 50 },
        pattern: { message: "Numeric and special characters are not allowed.", params: '^[a-zA-Z ]+$' }
    });

    self.IsActive = ko.observable(true);
    self.SectionType = ko.observable(null);
    self.StudyId = ko.observable(null);
    self.StudyParameters = ko.observableArray([]);

    self.Refresh = function (jsonData) {
        var mapping = {
            'StudyParameters': {
                create: function (options) {
                    return new StudyParameterVm(options.data);
                }
            }
        }

        ko.mapping.fromJS(jsonData, mapping, self);
    };

    self.IsNew = ko.computed(function () {
        return self.Id() == 0;
    });

    self.StudyParameterUrl = ko.pureComputed({
        read: function() {
            return '/StudyParameters/?sectionId=' + self.Id() + '&studyId=' + self.StudyId();
        },
        deferEvaluation: true
    });

    self.Refresh(jsonOfObject);

    self.MapToJson = function() {
        var json = {
            Id: self.Id(),
            Name: self.Name(),
            SortOrderId: self.SortOrderId(),
            IsActive: self.IsActive(),
            StudyId: self.StudyId(),
            SectionType: self.SectionType(),
            StudyParameters: self.GetStudyParametersJson()
        }
        return json;
    };

    self.GetStudyParametersJson = function () {
        var json = [];

        var i = 0;
        ko.utils.arrayForEach(self.StudyParameters(), function (item) {
            var studyParamJson = {};
            studyParamJson["Id"] = item.Id();
            studyParamJson["Name"] = item.Name();
            studyParamJson["ParameterId"] = item.Parameter().Id();
            studyParamJson["SectionId"] = self.Id();
            json[i] = studyParamJson;
            i++;
        });

        return json;
    }
};